﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Collections.ObjectModel;
using ELMWCFServiceClass.ELMWCF;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Regions;
using Microsoft.Practices.Composite.Modularity;
using System.Linq;
using System.Collections.Generic;
using ELMApplication.Common.Util;
using System.Windows.Data;

namespace SettingModule.Views.UserInfoSettingView
{
    public class UserInfoSettingPresentationModel : IUserInfoSettingPresentationModel
    {
        private ELMServiceClient _domaincontext;
        private readonly IEventAggregator _eventAggregator;
        private readonly IRegionManager regionManager;
        private readonly IModuleManager moduleManager;
        public UserInfoSettingPresentationModel(IUserInfoSettingView view, ELMServiceClient domaincontext, IEventAggregator eventAggregator, IRegionManager regionManage, IModuleManager moduleManager)
        {
            this._domaincontext = domaincontext;
            this._eventAggregator = eventAggregator;
            this.regionManager = regionManage;
            this.moduleManager = moduleManager;
            this.View = view;
            view.SetModel(this);
            //  InitialData();
        }
        public void InitialData()
        {
            _domaincontext = new ELMServiceClient();
            _domaincontext.GetAllContentTypeAsync();
            _domaincontext.GetAllContentTypeCompleted += (sender, data) =>
                {
                    ListDataSource = data.Result;
                };
            _domaincontext.GetAllELMListsAsync();
            _domaincontext.GetAllELMListsCompleted += (sd, e) =>
                {
                    AllELMList = e.Result;
                };
        }

        #region IUserInfoSettingPresentationModel Members

        public IUserInfoSettingView View
        {
            get;
            set;
        }
        private ObservableCollection<ELMField> _unSelectedData;
        public System.Collections.ObjectModel.ObservableCollection<ELMWCFServiceClass.ELMWCF.ELMField> UnSelectedData
        {
            get
            {
                return _unSelectedData;
            }
            set
            {
                _unSelectedData = value;
                NotifyPropertyChanged("UnSelectedData");
            }
        }
        private ObservableCollection<ELMField> _selectedData;
        public ObservableCollection<ELMWCFServiceClass.ELMWCF.ELMField> SelectedData
        {
            get
            {
                return _selectedData;
            }
            set
            {
                _selectedData = value;
                NotifyPropertyChanged("SelectedData");
            }
        }

        #endregion

        #region INotifyPropertyChanged Members

        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion

        #region IUserInfoSettingPresentationModel Members


        public void AddToSelected(ELMField data)
        {

            UnSelectedData.Remove(UnSelectedData.Single(c => c.FieldId == data.FieldId));
            SelectedData.Add(data);
            NotifyPropertyChanged("UnSelectedData");
            NotifyPropertyChanged("SelectedData");
            SetUnSelectedAndPagedDataAndGroup(UnSelectedData.ToArray());
        }


        public void RemoveFromSelected(ELMField data)
        {
            BusyMessage.Show();
            _domaincontext = new ELMServiceClient();
            _domaincontext.CheckFieldIsInUseAsync(data);
            _domaincontext.CheckFieldIsInUseCompleted += (sender, e) =>
                {
                    if (e.Error == null)
                    {
                        if (!e.Result)
                        {
                            SelectedData.Remove(SelectedData.Single(c => c.FieldId == data.FieldId));
                            //var tempArray = UnSelectedData.ToList();
                            //tempArray.Add(data);
                            UnSelectedData.Add(data);
                            NotifyPropertyChanged("UnSelectedData");
                            NotifyPropertyChanged("SelectedData");
                            SetUnSelectedAndPagedDataAndGroup(UnSelectedData.ToArray());
                        }
                        else
                        {
                            MessageBox.Show("该字段已被引用，并赋值，不可从该类型删除！");
                        }
                        BusyMessage.Close();
                    }
                    else
                    {
                        throw e.Error;
                    }
                };

        }
        private void SetDetialsValue(ContentType cType)
        {
            _domaincontext = new ELMServiceClient();
            _domaincontext.GetAllFieldAsync();
            _domaincontext.GetAllFieldCompleted += (sender, data) =>
                {
                    if (data.Error == null)
                    {
                        UnSelectedData = data.Result;
                        SelectedData = new ObservableCollection<ELMField>();
                        foreach (var key in cType.Fields.Keys)
                        {
                            UnSelectedData.Remove(UnSelectedData.Single(c => c.FieldId == key.FieldId));
                            SelectedData.Add(key);
                            NotifyPropertyChanged("UnSelectedData");
                            NotifyPropertyChanged("SelectedData");

                        }
                        SetUnSelectedAndPagedDataAndGroup(UnSelectedData.ToArray());
                    }

                };

        }
        private ObservableCollection<ContentType> _listDataSource;
        public ObservableCollection<ContentType> ListDataSource
        {
            get
            {
                return _listDataSource;
            }
            set
            {
                _listDataSource = value;
                NotifyPropertyChanged("ListDataSource");
            }
        }

        #endregion

        #region IUserInfoSettingPresentationModel Members


        public void ShowDetailSetting(Guid contentTypeId)
        {
            CW_ContentTypeDetial detail = new CW_ContentTypeDetial(this, contentTypeId);
            CurrentContentType = ListDataSource.Single(c => c.ContentId == contentTypeId);
            SetDetialsValue(CurrentContentType);
            detail.Show();
        }

        #endregion



        #region
        public void SaveData(Guid CurrentContentId)
        {
            BusyMessage.Show();
            Dictionary<ELMField, string> ds = new Dictionary<ELMField, string>();
            foreach (var item in SelectedData)
            {
               
                ds.Add(item, "");
            }
            _domaincontext = new ELMServiceClient();
            _domaincontext.UpdateContentTypeFieldsAsync(CurrentContentId, CurrentContentType.ContentName, ds);
            _domaincontext.UpdateContentTypeFieldsCompleted += (sender, data) =>
                {
                    if (data.Error == null)
                    {
                        InitialData();
                        MessageBox.Show("操作完成!");
                        BusyMessage.Close();
                    }
                };

        }

        #endregion



        #region IUserInfoSettingPresentationModel 成员

        private PagedCollectionView _unSelectedAndPagedData;
        public PagedCollectionView UnSelectedAndPagedData
        {
            get
            {
                return _unSelectedAndPagedData;
            }
            set
            {
                _unSelectedAndPagedData = value;
                NotifyPropertyChanged("UnSelectedAndPagedData");
            }
        }
        private void SetUnSelectedAndPagedDataAndGroup(ELMField[] unSelectedData)
        {
            PagedCollectionView pcv = new PagedCollectionView(unSelectedData);
            pcv.GroupDescriptions.Add(new PropertyGroupDescription("FieldGroupName"));
            UnSelectedAndPagedData = pcv;
        }

        #endregion

        #region IUserInfoSettingPresentationModel Members


        public void ChangeSelectedDataIndex(int seed)
        {
            if (SelectedData.Count > 1 && SelectedDataWhichIsSelected != null)
            {
                int oldindex = SelectedData.IndexOf(SelectedDataWhichIsSelected);
                if (oldindex + seed >= 0 && oldindex + seed <= SelectedData.Count - 1)
                {
                    int newindex = oldindex + seed;
                    ELMField[] copyOfSelected = new ELMField[SelectedData.Count];
                    SelectedData.CopyTo(copyOfSelected, 0);
                    var listdata = copyOfSelected.ToList();
                    listdata.RemoveAt(oldindex);
                    listdata.Insert(newindex, SelectedDataWhichIsSelected);
                    CollectionConvert<ELMField> cc = new CollectionConvert<ELMField>();

                    SelectedData = cc.IEnumerableConvertObservableCollection(listdata);
                }

            }
            NotifyPropertyChanged("SelectedData");
        }

        #endregion

        #region IUserInfoSettingPresentationModel Members

        private ELMField _selectedDataWhichIsSelected;
        public ELMField SelectedDataWhichIsSelected
        {
            get
            {
                return _selectedDataWhichIsSelected;
            }
            set
            {
                _selectedDataWhichIsSelected = value;
                if (_selectedDataWhichIsSelected != null)
                {
                    if (_selectedDataWhichIsSelected.ItemSourceGuid.HasValue&&AllELMList.Any(c => c.ELMListId == value.ItemSourceGuid.Value))//存在一个指定值，并且找得到该ID的列表，初始赋值
                    {
                        SelectedELmList = AllELMList.First(c => c.ELMListId == value.ItemSourceGuid.Value);
                    }
                    else
                    {
                        _selectedDataWhichIsSelected.ItemSourceGuid = null;
                        SelectedELmList = null;
                        ELMListItemFields = new ObservableCollection<ELMField>();
                        SelectedELMListItemField = null;
                    }
                    if (_selectedDataWhichIsSelected.DisplayMemberGuid.HasValue && SelectedELmList != null && SelectedELmList.ContentType.Fields.Keys.Any(c => c.FieldId == SelectedDataWhichIsSelected.DisplayMemberGuid.Value))
                    {

                        SelectedELMListItemField = SelectedELmList.ContentType.Fields.Keys.First(c => c.FieldId == SelectedDataWhichIsSelected.DisplayMemberGuid.Value);

                    }
                    else
                    {
                        _selectedDataWhichIsSelected.DisplayMemberGuid = null;
                    }
                }
               
                NotifyPropertyChanged("SelectedDataWhichIsSelected");
            }
        }

        #endregion

        #region IUserInfoSettingPresentationModel Members


        public void NewDetailSetting(Guid contentTypeId)
        {
            CW_ContentTypeDetial detail = new CW_ContentTypeDetial(this, contentTypeId);
            CurrentContentType = new ContentType()
            {
                ContentId = contentTypeId,
                Fields = new Dictionary<ELMField, string>(),
            };
            SetDetialsValue(CurrentContentType);

            detail.Show();
        }

        #endregion

        #region IUserInfoSettingPresentationModel Members

        private ContentType _currentContentType;
        public ContentType CurrentContentType
        {
            get
            {
                return _currentContentType;
            }
            set
            {
                _currentContentType = value;
                NotifyPropertyChanged("CurrentContentType");
            }
        }

        #endregion

        #region IUserInfoSettingPresentationModel Members

        private ObservableCollection<ELMList> _allELMList;
        public ObservableCollection<ELMList> AllELMList
        {
            get
            {
                return _allELMList;
            }
            set
            {
                _allELMList = value;
                NotifyPropertyChanged("AllELMList");
            }
        }
        private ELMList _selectedELMList;
        public ELMList SelectedELmList
        {
            get
            {
                return _selectedELMList;
            }
            set
            {
                _selectedELMList = value;
                if (_selectedELMList != null)
                {
                    CollectionConvert<ELMField> cc = new CollectionConvert<ELMField>();
                    ELMListItemFields = cc.IEnumerableConvertObservableCollection(_selectedELMList.ContentType.Fields.Keys);
                    if (SelectedDataWhichIsSelected.DisplayMemberGuid.HasValue)//向下初始赋值
                    {
                        if (ELMListItemFields.Any(c => c.DisplayMemberGuid == SelectedDataWhichIsSelected.DisplayMemberGuid.Value))
                        {
                            SelectedELMListItemField = ELMListItemFields.First(c => c.DisplayMemberGuid == SelectedDataWhichIsSelected.DisplayMemberGuid.Value);
                        }
                        else
                        {
                            SelectedDataWhichIsSelected.DisplayMemberGuid = null;
                        }


                    }
                    //向上反向更新
                    SelectedDataWhichIsSelected.ItemSourceGuid = _selectedELMList.ELMListId;
                }
                NotifyPropertyChanged("SelectedELmList");
            }
        }

        #endregion

        #region IUserInfoSettingPresentationModel Members

        private ObservableCollection<ELMField> _eMListItemFields;
        public ObservableCollection<ELMField> ELMListItemFields
        {
            get
            {
                return _eMListItemFields;
            }
            set
            {
                _eMListItemFields = value;
                NotifyPropertyChanged("ELMListItemFields");
            }
        }

        private ELMField _selectedELMListItemField;
        public ELMField SelectedELMListItemField
        {
            get
            {
                return _selectedELMListItemField;
            }
            set
            {
                _selectedELMListItemField = value;
                if (_selectedELMListItemField != null)
                {
                    SelectedDataWhichIsSelected.DisplayMemberGuid = _selectedELMListItemField.FieldId;
                }
                

                NotifyPropertyChanged("SelectedELMListItemField");
            }
        }

        #endregion
    }
}
